package com.jiayou.autoconfiguration

import com.jiayou.authention.AuthenticateHandler
import com.jiayou.server.ServerSocketServer
import com.jiayou.session.ByteServerSocketSession
import com.jiayou.session.DefaultServerSocketSession
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

/**
@author lishuang
@data   2021-04-24  15:39
@info   Ktor自动配置类
 */
@Configuration
@EnableConfigurationProperties(KtorSocketProperties::class)
@ConditionalOnProperty(prefix = "ktor", value = ["enable"], havingValue = "true")
class KtorSocketAutoconfiguration {


    //该自动配置类注入都是字符串类型的泛型
    //  T  ->  String
    //  T1 ->  String
    //  T2 ->  String
    @Configuration
    @ConditionalOnProperty(prefix = "ktor", value = ["mode"], havingValue = "simple")
    class SimpleTypeAutowired {
        @Bean
        @ConditionalOnClass(AuthenticateHandler::class)
        fun server(ktorSocketProperties: KtorSocketProperties, authenticateHandler: AuthenticateHandler<String, String>): ServerSocketServer<String, String, String> {
            return ServerSocketServer(
                DefaultServerSocketSession(
                    controller = ktorSocketProperties.controller,
                    authenticateHandler = authenticateHandler,
                    authenticateTime = ktorSocketProperties.authTime
                ), ktorSocketProperties.port
            )
        }
    }

    //该自动配置类注入传输数据是字节数组类型，身份凭据都是字符串类型的泛型
    //  T  ->  ByteArray
    //  T1 ->  String
    //  T2 ->  String
    @Configuration
    @ConditionalOnProperty(prefix = "ktor", value = ["mode"], havingValue = "byte")
    class ByteTypeAutowired {
        @Bean
        @ConditionalOnClass(AuthenticateHandler::class)
        fun server(ktorSocketProperties: KtorSocketProperties, authenticateHandler: AuthenticateHandler<String, String>): ServerSocketServer<ByteArray, String, String> {
            return ServerSocketServer(
                ByteServerSocketSession(
                    controller = ktorSocketProperties.controller,
                    authenticateHandler = authenticateHandler,
                    authenticateTime = ktorSocketProperties.authTime
                ), ktorSocketProperties.port
            )
        }
    }

}
